from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os
import datetime
import shutil
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4096 * 1024 * 1024

# 设置日志级别为 DEBUG
app.logger.setLevel(logging.DEBUG)

# 创建 RotatingFileHandler 对象，将日志记录到文件中
file_handler = RotatingFileHandler('app.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.DEBUG)

# 将文件处理程序添加到应用程序日志处理程序列表中
app.logger.addHandler(file_handler)

# 设置用户名和密码
USERNAME = 'sumz'
PASSWORD = 'Sumz'
UPLOAD_FOLDER = '/var/openebs/local/pvc-c15edebd-ac99-432b-b04e-91eee98c65d8/data/upload'
SYSNC_UPLOAD = 'C:\\Users\\wangk\\Desktop\\test\\'

def authenticate(username, password):
    # 检查用户名和密码是否匹配
    if username == USERNAME and password == PASSWORD:
        return True
    return False


@app.route('/upload', methods=['POST'])
def upload_file():
    # 获取认证信息
    auth = request.authorization
    if not auth or not authenticate(auth.username, auth.password):
        # 返回未认证的错误响应
        return jsonify({'error': 'Unauthorized'}), 401

    # 检查是否上传了文件
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400

    # 确保文件名安全
    filename = secure_filename(file.filename)
    # filename = file.filename

    # 创建日期目录
    current_date = datetime.datetime.now().date()
    date_folder = os.path.join(UPLOAD_FOLDER, current_date.strftime("%Y%m%d"))
    os.makedirs(date_folder, exist_ok=True)

    # 保存文件
    #file.save(filename)
    file.save(os.path.join(date_folder, filename))

    return jsonify({'message': 'File uploaded successfully'})

@app.route('/sysnc_upload', methods=['POST'])
def sysnc_upload():
    # 获取认证信息
    auth = request.authorization
    if not auth or not authenticate(auth.username, auth.password):
        # 返回未认证的错误响应
        return jsonify({'error': 'Unauthorized'}), 401

    # 检查是否上传了文件
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400

    # 确保文件名安全
    # filename = secure_filename(file.filename)
    filename = file.filename

    filename = filename.replace("\\","/")

    directory_ = os.path.dirname(filename)
    filename_ = os.path.basename(filename)

    # 创建目录
    # current_date = datetime.datetime.now().date()
    date_folder = os.path.join(SYSNC_UPLOAD, directory_)
    os.makedirs(date_folder, exist_ok=True)

    # 保存文件
    #file.save(filename)
    # file.save(os.path.join(date_folder, filename_))
    file_path = os.path.join(date_folder, filename_)
    with open(file_path, 'ab') as f:
        shutil.copyfileobj(file, f)

    app.logger.debug(f"【接收上传文件完成】:{file_path}")

    return jsonify({'message': 'File uploaded successfully'})

# 返回服务器端文件列表
@app.route('/list_files', methods=['GET'])
def list_files():
    file_sync_time = request.args.get('file_sync_time')
    client_name = request.args.get('client_name')

    file_paths = []
    current_date = datetime.datetime.strptime(file_sync_time, '%Y%m%d')
    end_date = datetime.datetime.utcnow()  # 获取当前日期时间
    while current_date <= end_date:
        year = current_date.strftime('%Y')
        month = current_date.strftime('%m')
        day = current_date.strftime('%d')
        print(f"Year: {year}, Month: {month}, Day: {day}")
        current_date += datetime.timedelta(days=1)

        file_path = os.path.join(SYSNC_UPLOAD, client_name, year, month, day)
        file_paths.append(file_path)

    file_list = []
    for file_paths_one in file_paths:
        app.logger.debug(f"【同步日期】:{file_paths_one}")
        for root, dirs, files in os.walk(file_paths_one):
            for file in files:
                file_list.append(os.path.relpath(os.path.join(root, file), SYSNC_UPLOAD))
    return jsonify(file_list)

if __name__ == "__main__":
    app.run(host='0.0.0.0')
